﻿using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;

using Game.Common;

namespace Game.Map
{
    [CollectionDataContract(Namespace="game",ItemName="GlobalItem")]
    public class GlobalItemCollection : Collection<IGlobalItem>
    {
        public event EventHandler<HasOwnerEventArgs> PlayerChanged;
        
        protected override void InsertItem(int index, IGlobalItem item)
        {
            if (!Contains(item))
            {
                base.InsertItem(index, item);
            }
            item.PlayerChanged += OnPlayerChanged;
        }
        
        protected override void RemoveItem(int index)
        {
            this[index].PlayerChanged -= OnPlayerChanged;
            base.RemoveItem(index);
        }
        
        void OnPlayerChanged(object sender, HasOwnerEventArgs e) 
        {
            DoPlayerChanged(e);
        }
        
        void DoPlayerChanged(HasOwnerEventArgs e)
        {
            if (PlayerChanged != null)
            {
                PlayerChanged(this, e);
            }
        }
    }
}
